package com.heima.behavlor.service.impl;
import java.util.Date;

import com.heima.behavlor.service.ApReadBehaviorService;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.wemedia.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

/**
 * @package com.heima.behavlor.service.impl
 * @Date 2022/3/8
 * @project heima-leadnews
 */
@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    ApBehaviorEntryServiceImpl apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 阅读行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {

        // 2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)

        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());


        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("articleId").is(dto.getArticleId()));
        ApReadBehavior apRoad = mongoTemplate.findOne(query, ApReadBehavior.class);
            //        3. 判断阅读行为是否存在
        if ( apRoad!= null) {
            // 4. 存在  将阅读行为的count字段加1 并修改
            Update update = new Update();
            update.set("count",apRoad.getCount()+1);
            mongoTemplate.updateMulti(query,update,ApReadBehavior.class);
        }else {
           // 不存在  创建阅读行为 并初始化count字段值为 1
            ApReadBehavior apReadBehavior = new ApReadBehavior();
            apReadBehavior.setEntryId(apBehaviorEntry.getId());
            apReadBehavior.setArticleId(dto.getArticleId());
            apReadBehavior.setCount(1);
            apReadBehavior.setCreatedTime(new Date());
            apReadBehavior.setUpdatedTime(new Date());
            mongoTemplate.save(apReadBehavior);
        }

        return ResponseResult.okResult();
    }
}
